<style lang="less">
  .ivu-poptip-rel{
    width: 100%;
  }
  .l-modalBg{
    background: #000;
    opacity: 0.8;
    position: fixed;
    width:100%;
    height: 100%;
    z-index:10000;
  }
</style>
<template>
  <div class="tem-div">
    <!--搜索-->
    <Card class="tem-card">
      <div class="search-item" :style="searchItemStyle">
      <Form ref="searchForm" label-position="right" inline :label-width="80">
        <FormItem label="设备号">
          <i-input placeholder="设备号" v-model="searchData.deviceNum"></i-input>
        </FormItem>
        <FormItem label="是否绑定">
          <i-select placeholder="是否绑定" filterable clearable v-model="searchData.bindType">
            <template v-for="item in bindTypes">
              <i-option :value="item.value" :key="item.label">{{item.label}}</i-option>
            </template>
          </i-select>
        </FormItem>
        <FormItem label="绑定车牌号">
          <i-input placeholder="车牌号" v-model="searchData.carNum"></i-input>
        </FormItem>
        <FormItem label="所属机构">
          <i-select placeholder="所属机构" filterable clearable v-model="searchData.orgName">
            <template v-for="item in orgList">
              <i-option :value="item.name" :key="item.label">{{item.name}}</i-option>
            </template>
          </i-select>
        </FormItem>
        <!--<FormItem label="车辆状态">
          <i-select placeholder="所属机构" filterable clearable v-model="searchData.status">
            <template v-for="item in statusList">
              <i-option :value="item.name">{{item.name}}</i-option>
            </template>
          </i-select>
        </FormItem>-->
      </Form>
      </div>
      <div class="search-btn" style="width: auto;">
        <hy-icon-btn @click="changeSearchDiv" :text="searchDiv?'收起更多':'展开更多'" :iconType="searchDiv?'chevron-up':'chevron-down'" iconSize="12"></hy-icon-btn>
        <Button type="primary" @click="search(1)" icon="search" :loading="searchListLoading">搜索</Button>
      </div>
    </Card>
    <!--按钮-->
    <Card class="tem-card">
      <div style="text-align: left">
        <i-button @click="giveAwayItem()">分发</i-button>
        <i-button @click="sameDevice()">手工同步</i-button>
        <i-button @click="exportList()">导出</i-button>
      </div>
    </Card>
    <!--表格-->
    <Card class="tem-card">
      <!--table部分-->
      <Table border :columns="columnsTitle" :loading="searchListLoading" :data="list" @on-selection-change="handleSelectionChange"></Table>
      <br>
      <!-- 分页 -->
      <Page :total="totalElement"
            :current="searchData.pageNum"
            size="small"
            show-elevator
            show-sizer
            show-total
            style="text-align: right;"
            @on-change="search"
            @on-page-size-change="pageSizeChange"
            :page-size-opts="pageSizeOpts"
      ></Page>
    </Card>
    <!--绑定-->
    <Modal v-model="bindModal.show" :mask-closable="false">
      <p slot="header">
        <span>{{bindModal.title}}</span>
      </p>
      <div style="text-align:center">
        <Form ref="form" :model="bindFormData" :rules="ruleValidate" :label-width="80">
          <hy-form-item :form="bindFormData" :formRow="bindFormItem"></hy-form-item>
        </Form>
      </div>
      <div slot="footer">
        <i-button type="success" size="large" :loading="actionLoading" @click="bind('form')" :disabled="!bindFormData.carNum">确定</i-button>
        <i-button size="large" @click="bindModal.show = false">取消</i-button>
      </div>
    </Modal>
    <!--分发-->
    <Modal v-model="giveAwayModal.show" :mask-closable="false">
      <p slot="header">
        <span>{{giveAwayModal.title}}</span>
      </p>
      <div style="text-align:center">
        <Form ref="form" :model="giveAwayFormData" :rules="ruleValidate" :label-width="80">
          <hy-form-item :form="giveAwayFormData" :formRow="giveAwayFormItem"></hy-form-item>
        </Form>
      </div>
      <div slot="footer">
        <i-button type="success" size="large" :loading="actionLoading" @click="giveAwayDevice('form')" :disabled="!giveAwayFormData.orgId">确定</i-button>
        <i-button size="large" @click="giveAwayModal.show = false">取消</i-button>
      </div>
    </Modal>
    <!--同步-->
    <div class="l-modalBg" v-if="sameModal.show">
      <div class="l-modal"></div>
    </div>
  </div>
</template>
<script>
  import fetch from './../service';
  import HyFormItem from '@/components/common/formItem/formItem.vue';
  import orgService from '../../../userManage/org/service';
  import carService from '../../car/service';
  import list from '@/js/mixins/list';
  // import $ from 'jquery';

  export default {
    components: {
      HyFormItem
    },
    mixins: [list],
    data () {
      return {
        loading: false,
        orgList: [],
        vehicleList: [],
        bindModal: {
          title: '',
          show: false
        },
        bindFormData: {
          carNum: '',
          deviceNum: ''
        },
        bindFormItem: [
          {
            key: 'carNum',
            title: '选择车辆',
            type: 'select',
            array: []
          }
        ],
        giveAwayModal: {
          title: '',
          show: false
        },
        giveAwayFormData: {
          orgId: ''
        },
        giveAwayFormItem: [
          {
            key: 'orgId',
            title: '选择机构',
            type: 'select',
            array: []
          }
        ],
        sameModal: {
          title: '同步设备',
          show: false
        },
        chooseIds: '',
        statusList: [
          {id: 0, name: '无法定位'},
          {id: 1, name: '信号中断'},
          {id: 2, name: '未定位'},
          {id: 3, name: '静止'},
          {id: 4, name: '行驶'},
          {id: 5, name: '未绑定'},
          {id: 6, name: '未启用'}
        ],
        ruleValidate: {
          carNum: [
            {required: true, message: '车辆不能为空', trigger: 'blur'}
          ]
        },
        // 查询条件
        searchObj: {
        },
        bindTypes: [{value: '1', label: '是'}, {value: '0', label: '否'}],
        businessTypeArray: [],
        columnsTitle: [
          {type: 'selection', width: 60, align: 'center'},
          {key: 'deviceNum', title: '设备号', width: 120},
          {key: 'status', title: '车辆状态', width: 120},
          {key: 'battery', title: '剩余电量（%）', width: 120},
          {key: 'orgName', title: '所属机构名称', width: 120},
          {
            title: '服务到期日期',
            width: 150,
            render: (h, params) => {
              let date = new Date(params.row.serviceTime);
              return (this._hyTool.DateFormat(date, 'yyyy-MM-dd'));
            }
          },
          {key: 'serviceType', title: '服务产品线', width: 120},
          {
            title: '是否绑定',
            width: 120,
            render: (h, params) => {
              return (this.bindStatus(params.row.bindType));
            }
          },
          {key: 'carNum', title: '绑定车牌号', width: 120},
          {key: 'waitForBindNum', title: '待绑定车辆', width: 120},
          {
            title: '待绑定车辆状态',
            width: 130,
            render: (h, params) => {
              return (this.bindStatus(params.row.waitForBindType));
            }
          },
          {key: 'offLine', title: '离线开始时间', width: 120},
          {key: 'attachInfo', title: '附件信息', width: 120},
          {
            title: '操作',
            key: 'action',
            width: 180,
            fixed: 'right',
            align: 'center',
            render: (h, params) => {
                if (params.row.carNum) {
                  return h('div', [this._hyTool.createIconBtn(h, params, this.unBindItem, '解绑车辆', 'scissors', '', {color: 'red'})]);
                } else {
                  return h('div', [this._hyTool.createIconBtn(h, params, this.bindItem, '绑定车辆', 'link', '', {color: '#57a3f3'})]);
                }
            }
          }
        ]
      };
    },
    created () {
      this.initOrgList();
    },
    methods: {
      _getList () {
        // 作用合并搜索条件
        fetch.getList(Object.assign(this.searchData, this.searchObj)).then(this.callback).catch();
      },
      handleSelectionChange (row) {
          let a = [];
          row.forEach(item => {
            a.push(item.deviceNum);
          });
         this.chooseIds = a;
         console.log(this.chooseIds);
      },
      async initOrgList () {
        let result;
        result = await orgService.getList({pageNum: 1, pageSize: 1000});
        this.orgList = result.data && result.data.content || [];
      },
      async initVehicleList () {
        let result;
        result = await carService.getList({bindFlag: 0, pageNum: 1, pageSize: 1000});
        this.vehicleList = result.data && result.data.content || [];
        let arr = [];
        if (this.vehicleList.length > 0) {
          this.vehicleList.forEach(item => {
              let a = {value: '', label: ''};
              a.value = item.carnum;
              a.label = item.carnum;
              arr.push(a);
          });
          this.bindFormItem[0].array = arr;
        }
      },
      // 绑定设备
      async bindItem (row) {
        this.bindModal.show = true;
        this.bindModal.title = '绑定车辆';
        this.bindFormData.deviceNum = row.deviceNum;
        await this.initVehicleList();
      },
      bind (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this._hyTool.cal(true);
            try {
              fetch.bindCar(this.bindFormData).then((data) => {
                this.$Notice.success({
                  title: '绑定成功'
                });
                this.search();
              }).catch((e) => {
              });
            } catch (e) {
            };
            this.bindModal.show = false;
            this._hyTool.cal(false);
          }
        });
      },
      unBindItem (row) {
        this.$Modal.confirm({
          title: '提示',
          content: '是否解绑该车辆：' + row.carNum,
          onOk: () => {
            let payload = {deviceNum: row.deviceNum};
            fetch.unbind(payload).then((data) => {
              this.$Notice.success({title: '解绑成功'});
              this.search();
            }).catch((e) => {
              console.log(e);
            });
          }
        });
      },
      // 分发
      async giveAwayItem () {
        if (this.chooseIds.length < 1) {
          this.$Notice.error({
            title: '请至少选择一个设备'
          });
          return;
        }
        this.giveAwayFormData.orgId = '';
        this.giveAwayModal.show = true;
        this.giveAwayModal.title = '分发设备';
        await this.initOrgList();
        let arr = [];
        if (this.orgList.length > 0) {
          this.orgList.forEach(item => {
            let a = {value: '', label: ''};
            a.value = item.id;
            a.label = item.name;
            arr.push(a);
          });
        }
        console.log(this.orgList);
        this.giveAwayFormItem[0].array = arr;
      },
      giveAwayDevice (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this._hyTool.cal(true);
            try {
              fetch.giveAway({orgId: this.giveAwayFormData.orgId}, this.chooseIds).then((data) => {
                this.$Notice.success({
                  title: '分发成功'
                });
                this.search();
              }).catch((e) => {
              });
            } catch (e) {
            };
            this.giveAwayModal.show = false;
            this._hyTool.cal(false);
          }
        });
      },
      // 分发
      async sameDevice () {
        this.$Modal.confirm({
          title: '提示',
          content: '是否立刻同步GPS设备？',
          onOk: () => {
            // this.sameModal.show = true;
          }
        });
      },
      // 导出
      async exportList () {
        this.$Modal.confirm({
          title: '提示',
          content: '是否导出当前页数据？',
          onOk: () => {
            fetch.export(this.searchData).then((data) => {
              // 此方法需要浏览器关闭拦截窗口
              window.open(data.url);
            });
          }
        });
      },
      // 绑定状态
      bindStatus (val) {
        let strInfo = '';
        switch (val) {
          case 1:
            strInfo = '是';
            break;
          case 0:
            strInfo = '否';
            break;
        }
        return strInfo;
      }
    }
  };
</script>
